package com.woniuxy.controller;

import com.woniuxy.entity.Cart;
import com.woniuxy.service.CartService;
import com.woniuxy.utils.JWTUtil;
import com.woniuxy.utils.ResponseResults;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/cart")
public class CartController {

    @Resource
    private CartService cartService;

    // 查询当前用户的全部购物车信息
    @GetMapping("/all")
    public ResponseResults<List<Cart>> all(HttpServletRequest request) {

        System.out.println("进入all：");
        String token = request.getHeader("authorization");
        int getuid = JWTUtil.getuid(token);
        return cartService.getAll(getuid);
    }

    @PostMapping("/add")
    public ResponseResults<Boolean> add(
            // 封裝好的cart对象
            @RequestBody Cart cart,
            HttpServletRequest request) {

        // 获取token
        String token = request.getHeader("authorization");
        System.out.println("输出token：" + token);
        // 从token中获取当前用户uid
        int getuid = JWTUtil.getuid(token);
        // 将用户uid存入cart
        cart.setUid(getuid);
        return cartService.addCart(cart);
    }

    // axios的post、put请求都是讲对象转换成json字符串传递
    @PutMapping("/update")
    public ResponseResults<Boolean> update( @RequestBody Cart cart) {

        System.out.println("cart数据："+ cart.toString());
        return cartService.updateNum(cart);
    }

    @DeleteMapping("/del/{id}")
    public ResponseResults<Boolean> del(@PathVariable("id") int id) {

        System.out.println("传入的id"+id);
        return cartService.del(id);
    }


}
